package com.sumer.psychology.space.infrastructure.port.adapter;

import com.sumer.psychology.common.Assert;
import com.sumer.psychology.common.BusinessException;
import com.sumer.psychology.sharing.domain.model.SharedResource;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

/**
 * User: zhenguang.zhu
 * Date: 2014/12/3
 * Time: 9:07
 */
public class HttpSharedResourceAdaptor implements SharedResourceAdaptor {
    private String urlTemplate;

    public HttpSharedResourceAdaptor(String urlTemplate) {
        this.urlTemplate = urlTemplate;
    }

    @Override
    public SharedResource sharedResource(String aResourceId) {
        Assert.notEmpty(aResourceId);

        SharedResource sharedResource = null;
        try {
            Client client = ClientBuilder.newClient();
            Response response = client.target(urlTemplate)
                    .resolveTemplate("id", aResourceId)
                    .request(MediaType.APPLICATION_JSON_TYPE)
                    .get();

            if (response.getStatus() == 200) {
                sharedResource = new SharedResourceTranslator().toSharedResourceFromRepresentation(
                        response.readEntity(String.class));
            } else if (response.getStatus() == 204) {
                sharedResource = null;
            } else {
                throw new IllegalStateException(
                        "访问共享资源出现失败信息："
                                + aResourceId
                                + "状态码是："
                                + response.getStatus());
            }
        } catch (Exception e) {
            throw new BusinessException(
                    "获得User信息失败，原因是:" + e.getMessage(), e);
        }
        return sharedResource;
    }
}
